<?php
/**
 * Created by PhpStorm.
 * User: Bostin
 * Date: 2019-02-15
 * Time: 10:48
 */

namespace Bostin\Translator\Sdk;


use GuzzleHttp\Client;

/**
 * Class Microsoft
 * @package Bostin\Translator\Sdk
 */
class Microsoft
{
    /**
     * @var string
     */
    protected $api = 'https://api.cognitive.microsofttranslator.com/translate';

    /**
     * @var
     */
    protected $client;

    /**
     * @var array
     */
    protected $config;

    /**
     * Microsoft constructor.
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        $this->config = $config;
    }

    /**
     * @return Client
     */
    private function getClient(): Client
    {
        if (is_null($this->client)) {
            $headers = [];
            if (!empty($this->config['Ocp-Apim-Subscription-Key'])) {
                $headers['Ocp-Apim-Subscription-Key'] = $this->config['Ocp-Apim-Subscription-Key'];
            } else if (!empty($this->config['Ocp-Api-Subscription-Key']) && !empty($this->config['Ocp-Apim-Subscription-Region'])) {
                $headers['Ocp-Api-Subscription-Key'] = $this->config['Ocp-Api-Subscription-Key'];
                $headers['Ocp-Apim-Subscription-Region'] = $this->config['Ocp-Apim-Subscription-Region'];
            }

            $config = $this->config['guzzle'] ?? [];
            $config['headers'] = array_merge($config['headers'] ?? [], $headers);

            $this->client = new Client($config);
        }
        return $this->client;
    }

    /**
     * @param string $sourceText
     * @param string $source
     * @param string $target
     * @return string|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function textTranslate(string $sourceText, string $source, string $target): ?string
    {
        $result = $this->request(['text' => $sourceText, 'from' => $source, 'to' => $target]);
        return $result[0]['translations'][0]['text'] ?? null;
    }

    /**
     * @param array $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function request(array $params): array
    {
        $params = [
            'api-version' => '3.0',
            'from' => $params['from'] ?? 'auto',
            'to' => $params['to'] ?? 'en',
        ];

        $json = [['Text' => $params['text']]];

        $body = (string)$this->getClient()->request('POST', $this->api . '?' . http_build_query($params), ['json' => $json])->getBody();
        return json_decode($body, true);
    }
}